<template>
  <div class="group-store">
    <div class="table-title">
      <el-button type="primary" @click="handleAdd" data-auth="store_goods_add">添加商品</el-button>
    </div>
    <div class="table-content">
      <el-table
        border
        :data="tableData"
        style="width: 100%">
        <el-table-column
          label="产品名称"
          prop="Name">
        </el-table-column>
        <el-table-column
          label="消费类别"
          prop="TypeName">
        </el-table-column>
        <el-table-column
          label="单位"
          prop="Unit">
        </el-table-column>
        <el-table-column
          label="单价"
          prop="UnitPrice">
        </el-table-column>
        <el-table-column
          label="简介"
          prop="Describe">
        </el-table-column>
        <el-table-column
          label="状态"
          prop="IsOnLine">
          <template slot-scope="scope">
            <span>{{scope.row.IsOnLine?'上架':'已下架'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)" data-auth="store_goods_modify">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)" data-auth="store_goods_delete">删除</el-button>
            <el-button
              size="mini"
              type="primary"
							v-if="!scope.row.IsOnLine"
              @click="handleOnline(scope.$index, scope.row)" data-auth="store_goods_putaway">上架</el-button>
						<el-button
							size="mini"
							v-if="scope.row.IsOnLine"
							@click="handleOffline(scope.$index, scope.row)" data-auth="store_goods_putaway">下架</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="table-page">
			<el-pagination
			  background
				@size-change="changePage"
      	@current-change="getList"
      	:current-page.sync="searchData.pageIndex"
      	:page-sizes="[100, 200, 300, 400]"
			  layout="total,prev, pager, next"
			  :total="pageTotal">
			</el-pagination>
    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="roomShow"
      width="560px"
      center>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="商品名称：" prop="Name">
          <el-input v-model="ruleForm.Name"></el-input>
        </el-form-item>
        <el-form-item label="商品类别：" prop="Type">
          <el-select v-model="ruleForm.Type" placeholder="请选择商品类别">
            <el-option label="休闲娱乐" :value="6701"></el-option>
            <el-option label="房间消费" :value="6702"></el-option>
            <el-option label="土特产" :value="6703"></el-option>
            <el-option label="旅游交通" :value="6704"></el-option>
            <el-option label="餐饮" :value="6705"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品单价：" prop="UnitPrice">
          <el-input v-model="ruleForm.UnitPrice"></el-input>
        </el-form-item>
        <el-form-item label=" 商品单位：" prop="Unit">
          <el-input v-model="ruleForm.Unit"></el-input>
        </el-form-item>
        <el-form-item label=" 商品简介：" prop="Describe">
          <el-input v-model="ruleForm.Describe"></el-input>
        </el-form-item>
        <el-form-item label="商品图片：" prop="PhotoList">
          <el-upload
            class="avatar-uploader"
            action="/"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-remove="handleRemove">
            <el-button type="primary">点击上传商品图片</el-button>
          </el-upload>
          <div class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率256*256)</div>
          <span class="upload-imglist" v-for="(m,index) in ruleForm.ImageList">
            <!-- <el-checkbox v-model="m.IsMasterPhoto" label="设置为封面图" @change="setIsMasterPhoto(m)"></el-checkbox> -->
            <img v-if="ruleForm.ImageList.length>0" :src="m.Url">
            <i class="el-icon-circle-close-outline" @click="ruleForm.ImageList.splice(index,1)"></i>
          </span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnSave('ruleForm')">保存</el-button>
        <el-button @click="roomShow = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        dialogTitle:'',
        roomShow:false,
        dialogColTitle:'',
        roomColShow:false,
        fileList: [],
        pageTotal:0,
        searchData:{
          hotelId:JSON.parse(sessionStorage.getItem('nowmenu')).Id,
          pageIndex:1,
          pageSize:10
        },
        tableData: [],
        ruleForm: {
          Name: "",
          HotelId: JSON.parse(sessionStorage.getItem('nowmenu')).Id,
          Type: "",
          Describe: "",
          UnitPrice: "",
          ImageList:"",
          Unit: "",
        },
        colForm: {
          name: '',
          phone: '',
          city: '',
          address: '',
          resource:false
        },
        rules: {
          Name: [
            { required: true, message: '请输入产品名称', trigger: 'blur' },
          ],
          Type: [
            { required: true,type:'number', message: '请选择商品类别', trigger: 'change' }
          ],
          Describe: [
            { required: true, message: '请输入商品简介', trigger: 'blur' },
          ],
          UnitPrice: [
            { required: true, message: '请输入商品单价', trigger: 'blur' },
          ],
          Unit: [
            { required: true, message: '请选择商品单位', trigger: 'blur' }
          ],
        }
      }
    },
    created(){
      this.initList();
    },
    methods:{
      querylistbypid(id,type,reset){
        if(reset){
          this.addData[reset]='';
        }
        this.$ajax.querylistbypid({pid:id}).then(res=>{
          if(res.Success){
            this[type]=res.Data;
          }
        })
      },
      initList(){
        this.searchData.pageIndex=1;
        this.roomShow=false;
        this.roomColShow=false;
        this.getList();
      },
      changePage(size){
        this.searchData.pageIndex=1;
        this.searchData.pageSize=size;
        this.getList();
      },
      getList(){
        this.$ajax.GetSingleProductByPage(this.searchData).then(res=>{
          if(res.Success){
            this.tableData=res.Data.PagedData;
            this.pageTotal=res.Data.TotalCount;
          }
        })
      },
      handleRemove(file, fileList){
         console.log(file, fileList);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'||file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
          return
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return
        }
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onloadend = ()=>{
          file.url = reader.result;
          this.$ajax.upLoadImg({FileName:file.name,FileBase64:file.url.split(',')[1]}).then(res=>{
            if(res.Success){
                this.ruleForm.ImageList.push(
                  {
                    Name: file.name,
                    Url: res.Data,
                    IsMasterPhoto: false
                  }
                );
            }
          })
        }
        return false;
      },
      setIsMasterPhoto(m){
        _.map(this.ruleForm.ImageList,val=>{
          if(val.Name!==m.Name){
            val.IsMasterPhoto=false;
          }
        })
      },
      resetForm(formName) {
        if(!this.$refs[formName]){return};
        this.$refs[formName].resetFields();
      },
      handleAdd(index, row) {
        this.dialogTitle='添加商品';
        this.resetForm('ruleForm');
        this.ruleForm={
          Name: "",
          HotelId: JSON.parse(sessionStorage.getItem('nowmenu')).Id,
          Type: "",
          Describe: "",
          UnitPrice: "",
          ImageList:[],
          Unit: ""
        };
        this.roomShow=true;
      },
      handleEdit(index, row) {
        this.dialogTitle='编辑商品';
        this.resetForm('ruleForm');
        this.$ajax.GetSingleProductById({id:row.Id}).then(res=>{
          if(res.Success){
            this.ruleForm=res.Data;
            this.roomShow=true;
          }
        })
      },
      handleDelete(index, row) {
        this.deleteShow('确认删除此商品?',row.Id,'DeleteSingleProduct')
      },
      deleteShow(title,id,api){
        this.$confirm(title, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          let data={
            id:api==='DeleteRoomCategoryPolicy'?id.Id:id
          };
          this.$ajax[api](data).then(res=>{
            if(res.Success){
              this.$message({
                type: 'success',
                message: '已删除!'
              });
              this.initList();
              if(api==='DeleteRoomCategoryPolicy'){this.gettableColData(id.RoomCategoryId);}
            }
          })
        }).catch(() => {
        });
      },
      triggerShow(title,row){
        this.$confirm(title, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.TriggerHotelInfo(row);
        }).catch(() => {
        });
      },
      handleOnline(index, row) {
        this.triggerShow(row.IsOnLine?'确认下架！':'确认上架！',row)
      },
      handleOffline(index,row){
        this.triggerShow(row.IsOnLine?'确认下架！':'确认上架！',row)
      },
      TriggerHotelInfo({Id,IsOnLine}){
        let data={
          id:Id,
          isOnLine:!IsOnLine
        }
        this.$ajax.TriggerSingleProduct(data).then(res=>{
          if(res.Success){
            this.$message.success(IsOnLine?'已下架！':'已上架！');
            this.initList();
          }
        })
      },
      btnSave(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$ajax.SaveSingleProduct(this.ruleForm).then(res=>{
              if(res.Success){
                this.$message.success(this.dialogTitle+'成功!');
                this.$refs[formName].resetFields();
                this.initList();
              }
            })
          } else {
            return false;
          }
        });
      }
    }
  }
</script>
